package com.my.serviceimpl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.my.bean.*;
import com.my.mapper.UserMapper;
import com.my.service.MenuResourseService;
import com.my.service.RoleService;
import com.my.service.RoleUserService;
import com.my.service.UserService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 张子艺
 * @since 2018-08-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    RoleService roleService;
    @Autowired
    RoleUserService roleUserService;
    @Autowired
    MenuResourseService menuResourseService;
    //登陆
    @Override
    public String login(User user, HttpSession session) {
        Map<String, Object> jsonMap = new HashMap<String, Object>();
        if(user.getUsername()==null||user.getUsername().equals("")){
            //返回出提示消息
            jsonMap.put("flag",false);
            jsonMap.put("msg", "请输入账号");
            return JSON.toJSONString(jsonMap);
        }
        if(user.getPassword()==null||user.getPassword().equals("")){
            //返回出提示消息
            jsonMap.put("flag",false);
            jsonMap.put("msg", "请输入密码");
            return JSON.toJSONString(jsonMap);
        }

        //根据输入账户 查询数据库
        List<User> userList=baseMapper.findUserByUsername(user);
        //如果存在该用户
        if (userList.size()>0){
            //如果该用户的密码和输入的密码一样 则登陆成功
            boolean flag=userList.get(0).getPassword().equals(user.getPassword());
            //数据库存在  登陆成功
            if (flag){
                //给该用户的角色 关联上该角色所拥有的菜单
                userList.get(0).getRoles().setMenuResourses(menuResourseService.findMenuByRole(userList.get(0).getRoles()));
                System.err.print(userList.get(0).toString());
                //把登陆成功的用户 存进session
                session.setAttribute("user",userList.get(0));
                //返回出提示消息
                jsonMap.put("flag",true);
                jsonMap.put("msg", "登陆成功");
                return JSON.toJSONString(jsonMap);
            }else{
                //返回出提示消息
                jsonMap.put("flag",false);
                jsonMap.put("msg", "密码错误");
                return JSON.toJSONString(jsonMap);
            }

        }else{
            //返回出提示消息
            jsonMap.put("flag",false);
            jsonMap.put("msg", "没有该账户");
            return JSON.toJSONString(jsonMap);
        }
    }

    @Override
    public ResultPage<User> selectMyPage(VoPage voPage,User user) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1)*voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<User> list = baseMapper.selectMyPage(paramMap,user);
        Integer count = baseMapper.countMyPage2(paramMap,user);
        ResultPage<User>resultPage=new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    @Override
    public ResultPage<User> findUserAndRole(VoPage voPage,User user,Long areaid,boolean admin) {
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("page", (voPage.getPage() - 1)*voPage.getLimit());
        paramMap.put("limit", voPage.getLimit());
        List<User> list = baseMapper.findUserAndRole(paramMap,user,areaid,admin);
        Integer count = baseMapper.countMyPage(paramMap,user,areaid,admin);
        ResultPage<User>resultPage=new ResultPage<>();
        resultPage.setCode(0);
        resultPage.setCount(count);
        resultPage.setMsg("成功");
        resultPage.setData(list);
        return resultPage;
    }

    @Override
    public String insertUser(String param) {
        //把传过来的json字符串转成Map集合
        Map mapObj = JSONObject.parseObject(param,Map.class);
        long roleId=Long.parseLong(mapObj.get("roleId")+"");
        String username=(String) mapObj.get("username");
        String password =(String) mapObj.get("password");
        //Long areaId =Long.parseLong( mapObj.get("areaId")+"");
        //String appoint = (String) mapObj.get("appoint");
        Map map=new HashMap<>();
        map.put("username",username);
        List<User> users=this.selectByMap(map);
        if (users.size()>0){
            return "该账户已存在";
        }


        User user=new User();
        user.setCreateTime(new Date().getTime());
        user.setPassword(password);
        user.setUsername(username);
        //user.setAreaId(areaId);
        //user.setAppoint(appoint);

        if(this.insert(user)){
            RoleUser roleUser=new RoleUser();
            roleUser.setRoleId(roleId);
            roleUser.setUserId(user.getId());
            if(roleUserService.insert(roleUser)){
                if (baseMapper.updateAreaId(user.getId())==1){
                    return  "添加成功";
                }

            }

        }
        return "添加失败";
    }

    @Override
    @Transactional(rollbackFor = {SQLException.class})
    public String deleteUser(Long id) throws SQLException {
        Map map=new HashMap<>();
        map.put("user_id",id);
        if(roleUserService.deleteByMap(map)){
            if(this.deleteById(id)){
                return "删除成功";
            };
        };
        throw  new  SQLException();
    }



    //修改
//    @Override
//    public boolean updateAreaId() {
//        return baseMapper.updateAreaId();
//    }


}
